<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="18">
        <el-input v-model="filterText" placeholder="分类名称" clearable @input="filterTree" />
      </el-col>
      <el-col :span="6">
        <el-button @click="handleExpand">
          {{ isExpand ? '折叠' : '展开' }}
        </el-button>
      </el-col>
    </el-row>
    <el-scrollbar>
      <el-tree
        style="margin-top: 15px"
        ref="categoryTreeRef"
        :data="treeData"
        node-key="id"
        highlight-current
        :props="{ label: 'name', value: 'id' }"
        :default-expand-all="isExpand"
        :current-node-key="defaultCategoryId"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
      >
      </el-tree>
    </el-scrollbar>
  </div>
</template>

<script>
import categoryApi from '@/api/category'

export default {
  data() {
    return {
      filterText: '',
      isExpand: true,
      treeData: [],
      defaultCategoryId: 1
    }
  },
  created() {
    this.getCategoryList()
    this.$emit('getCategoryId', this.defaultCategoryId)
  },
  watch: {
    treeData(val) {
      this.defaultCategoryId = val[0].id || 7
    },
    filterText(val) {
      this.$refs.categoryTreeRef.filter(val)
    }
  },
  methods: {
    async getCategoryList() {
      const res = await categoryApi.getCategory()
      this.treeData = res.data
    },
    filterTree() {
      this.$refs.categoryTreeRef.filter(this.filterText)
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    handleExpand() {
      this.isExpand = !this.isExpand
      const nodes = this.$refs.categoryTreeRef.store._getAllNodes()
      for (let i = 0; i < nodes.length; i++) {
        nodes[i].expanded = this.isExpand
      }
    },
    handleNodeClick(data) {
      this.$emit('getCategoryId', data.id)
    }
  }
}
</script>
